package com.movitech.mobile.cz.base.purchase.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.modules.config.CallBackAbutmentTypeEnum;
import com.movitech.mobile.cz.base.modules.config.PurchasePlanFlowTypeEnum;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.bizvo.ContactPlanListResponseVO;
import com.movitech.mobile.cz.base.purchase.bizvo.PContactPlanVo;
import com.movitech.mobile.cz.base.purchase.entity.PContactPlan;
import com.movitech.mobile.cz.base.purchase.entity.PSpecialPurchasePlan;
import com.movitech.mobile.cz.base.purchase.entity.PStrategicPurchaseContact;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtPContactPlan;
import com.movitech.mobile.cz.base.purchase.entity.ext.PContactPlanFindRequest;
import com.movitech.mobile.cz.base.purchase.entity.ext.PContactPlanGetRequest;
import com.movitech.mobile.cz.base.purchase.mapper.PContactPlanMapper;
import com.movitech.mobile.cz.base.purchase.mapper.PSpecialPurchasePlanMapper;
import com.movitech.mobile.cz.base.purchase.mapper.ext.ExtPContactPlanMapper;
import com.movitech.mobile.cz.base.purchase.service.PContactPlanService;
import com.movitech.mobile.cz.base.purchase.service.PStrategicPurchaseContactService;
import com.movitech.mobile.cz.base.purchase.service.SAbutmentLogsService;
import com.movitech.mobile.cz.base.sys.entity.SCompany;
import com.movitech.mobile.cz.base.sys.entity.SProject;
import com.movitech.mobile.cz.base.sys.entity.SRegionalCompany;
import com.movitech.mobile.cz.base.sys.entity.ext.SRegionCompanyRequestVO;
import com.movitech.mobile.cz.base.sys.service.SCompanyService;
import com.movitech.mobile.cz.base.sys.service.SProjectService;
import com.movitech.mobile.cz.base.sys.service.SRegionalCompanyService;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 合约规划 服务实现类
 * </p>
 *
 * @author Movitech Mobile
 * @since 2018-03-08
 */
@Service
public class PContactPlanServiceImpl extends ServiceImpl<PContactPlanMapper, PContactPlan> implements PContactPlanService {

    private final static Logger logger = Logger.getLogger(PContactPlanServiceImpl.class);

    @Autowired
    private ExtPContactPlanMapper extPContactPlanMapper;

    @Autowired
    private PContactPlanMapper pContactPlanMapper;

    @Autowired
    @Qualifier("sProjectService")
    private SProjectService sProjectService;
    @Autowired
    @Qualifier("sCompanyService")
    private SCompanyService sCompanyService;
    @Autowired
    @Qualifier("sAbutmentLogsService")
    private SAbutmentLogsService sAbutmentLogsService;

    @Autowired
    @Qualifier("sRegionalCompanyService")
    private SRegionalCompanyService sRegionalCompanyService;

    @Autowired
    private PSpecialPurchasePlanMapper pSpecialPurchasePlanMapper;

    @Autowired
    private PStrategicPurchaseContactService pStrategicPurchaseContactService;

    @Override
    public PageCode findContractPlanList(PContactPlanFindRequest pContactPlanFindRequest) throws Exception {

        try {
            if (pContactPlanFindRequest.getPageFlag() == 0) {//不分页
                pContactPlanFindRequest.setPageSize(10);
            }

            LicenseUtil.INSTANCE.validate();
            PageCode pageCode = new PageCode(pContactPlanFindRequest.getPageNumber(), pContactPlanFindRequest.getPageSize());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
            map.put("pageSize", pageCode.getPageSize());
            map.put("pageFlag", pContactPlanFindRequest.getPageFlag());
            map.put("planStatus", pContactPlanFindRequest.getPlanStatus());
            map.put("regionalCompanyId", pContactPlanFindRequest.getRegionalCompanyId());
            map.put("projectId", pContactPlanFindRequest.getProjectId());
            map.put("projectByStage", pContactPlanFindRequest.getProjectByStage());
            map.put("contractName", pContactPlanFindRequest.getContractName());

            if (pContactPlanFindRequest.getPageFlag() == 1) {
                Integer count = extPContactPlanMapper.findContractPlanListCount(map);
                pageCode.setCount(count == null ? 0 : count);
            }

            List<ExtPContactPlan> ls = extPContactPlanMapper.findContractPlanList(map);
            if (StringUtils.isNotEmpty(pContactPlanFindRequest.getPlanId())) {
                PSpecialPurchasePlan pSpecialPurchasePlan = pSpecialPurchasePlanMapper.selectById(pContactPlanFindRequest.getPlanId());
                if (StringUtils.isNotEmpty(pSpecialPurchasePlan.getContactPlanId())) {
                    if (pSpecialPurchasePlan.getProjectId().equals(pContactPlanFindRequest.getProjectId())) {
                        String contractId = pSpecialPurchasePlan.getContactPlanId();
                        String[] contactIds = contractId.split(",");
                        for (String conId : contactIds) {
                            ExtPContactPlan extPContactPlan = extPContactPlanMapper.getPContractPlanById(conId);
                            if (extPContactPlan != null) {
                                ls.add(extPContactPlan);
                            }
                        }

                    }
                }
            }
            List<ContactPlanListResponseVO> result = new ArrayList<>();

            /*if (ls == null || ls.size() == 0) {
                throw new RuntimeException("没有可用招标项！", new ServiceThrowable());
            }*/

            if (ls != null && ls.size() > 0) {
                result = ListObjCopyUtil.copyTo(ls, ContactPlanListResponseVO.class);
            }

            pageCode.setList(result);

            return pageCode;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("===============findContractPlanList==========e:======" + e.getMessage());
            throw new Exception(e);
        }

    }

    @Override
    public ExtPContactPlan getPContractPlanById(String contractPlanId) {
        ExtPContactPlan extPContactPlan = extPContactPlanMapper.getPContractPlanById(contractPlanId);
        return extPContactPlan;
    }

    @Override
    public Double getBudgetByContractId(String contractId) {
        EntityWrapper entityWrapper = new EntityWrapper();
        PContactPlan pContactPlan = new PContactPlan();
        pContactPlan.setContractId(contractId);
        entityWrapper.setSqlSelect("plan_budget_prices");
        entityWrapper.setEntity(pContactPlan);
        List<PContactPlan> pContactPlans = selectList(entityWrapper);
        if (CollectionUtils.isEmpty(pContactPlans))
            return null;
        else {
            return pContactPlans.get(0).getPlanBudgetPrices();
        }
    }

    @Override
    public boolean insertOrUpdateSpecialPurchasePlan(PContactPlan contactPlan) {
        if (StringUtils.isNotBlank(contactPlan.getId())) {
            PContactPlan pContactPlan = pContactPlanMapper.selectById(contactPlan.getId());
            if (StringUtils.isNotBlank(contactPlan.getRegionalCompanyId())) {
                pContactPlan.setRegionalCompanyId(contactPlan.getRegionalCompanyId());
            }
            if (StringUtils.isNotBlank(contactPlan.getProjectId())) {
                pContactPlan.setProjectId(contactPlan.getProjectId());
            }
            if (StringUtils.isNotBlank(contactPlan.getProjectByStage())) {
                pContactPlan.setProjectByStage(contactPlan.getProjectByStage());
            }
            if (StringUtils.isNotBlank(contactPlan.getContractId())) {
                pContactPlan.setContractId(contactPlan.getContractId());
            }
            if (StringUtils.isNotBlank(contactPlan.getContractName())) {
                pContactPlan.setContractName(contactPlan.getContractName());
            }
            if (StringUtils.isNotBlank(contactPlan.getContractCode())) {
                pContactPlan.setContractCode(contactPlan.getContractCode());
            }
            boolean i = this.insertOrUpdate(pContactPlan);
            return i;
        }
        return false;
    }

    @Override
    public RestReturnResult getPContractPlanByIds(PContactPlanGetRequest pContactPlanGetRequest) {
        RestReturnResult restResult = RestReturnResult.success();
        ExtPContactPlan result = new ExtPContactPlan();
        List<ExtPContactPlan> extPContactPlans = extPContactPlanMapper.getPContractPlanByIds(pContactPlanGetRequest);
        if (extPContactPlans == null || extPContactPlans.size() <= 0) {
            restResult.setCode(CommonConstants.FAIL);
            restResult.setMsg(CommonConstants.ERROR_DESC_DATA_NOT_EXISTEN);
            return restResult;
        }
        LicenseUtil.INSTANCE.validate();
        int index = 0;
        String projectId = null;
        for (ExtPContactPlan contactPlan : extPContactPlans) {
            if (projectId != null && !projectId.equals(contactPlan.getProjectId())) {
                restResult.setCode(CommonConstants.FAIL);
                restResult.setMsg(CommonConstants.ERROR_DESC_GET_DEFFERENT_PROJECT_DATA);
                return restResult;
            }
            projectId = contactPlan.getProjectId();
            if (index == 0) {
                result.setProjectId(contactPlan.getProjectId());
                result.setProjectName(contactPlan.getProjectName());
                result.setRegionalCompanyId(contactPlan.getRegionalCompanyId());
                result.setRegionalCompanyName(contactPlan.getRegionalCompanyName());

                result.setContractPlanIds(contactPlan.getId());
                result.setContractId(contactPlan.getContractId());
                result.setContractName(contactPlan.getContractName());
                result.setContractCodes(contactPlan.getContractCode());
                result.setProjectByStage(contactPlan.getProjectByStage());
            } else {
                result.setContractPlanIds(result.getContractPlanIds() + "," + contactPlan.getId());
                result.setContractId(result.getContractId() + "," + contactPlan.getContractId());
                result.setContractName(result.getContractName() + "," + contactPlan.getContractName());
                result.setContractCodes(result.getContractCodes() + "," + contactPlan.getContractCode());
                result.setProjectByStage(result.getProjectByStage() + "," + contactPlan.getProjectByStage());
            }
            index++;
        }
        restResult.setData(result);
        return restResult;
    }

    @Override
    public boolean addPContactPlan(PContactPlan pContactPlan) {

        if (pContactPlan != null) {
            if (StringUtils.isBlank(pContactPlan.getId())) {
                pContactPlan.setId(IdGenUtils.uuid());
            }

            String userId = UserUtils.getCurrentUserId();
            Date createDate = new Date();
            pContactPlan.setCreateBy(userId);
            pContactPlan.setCreateDate(createDate);
            pContactPlan.setUpdateBy(userId);
            pContactPlan.setUpdateDate(createDate);
            pContactPlan.setDelFlag(CommonConstants.NO_INTEGER);

            int i = baseMapper.insert(pContactPlan);

            return i > 0;
        }

        return false;
    }

    @Override
    public boolean updatePContactPlan(PContactPlan pContactPlan) {

        if (StringUtils.isNotBlank(pContactPlan.getId())) {
            String userId = UserUtils.getCurrentUserId();
            Date updateDate = new Date();
            pContactPlan.setUpdateBy(userId);
            pContactPlan.setUpdateDate(updateDate);

            int i = baseMapper.updateById(pContactPlan);

            return i > 0;
        }

        return false;
    }

    @Override
    public void batchSave(List<PContactPlanVo> pContactPlanList) {
        try {
            if (pContactPlanList != null && pContactPlanList.size() > 0) {
                if (CollectionUtils.isNotEmpty(pContactPlanList)) {
                    for (PContactPlanVo pContactPlan : pContactPlanList) {
                        SProject sProject = sProjectService.selectByStageCode(pContactPlan.getProjectByStageCode());
                        if (sProject != null) {
                            pContactPlan.setProjectCode(sProject.getProjectCode());
                            pContactPlan.setProjectName(sProject.getProjectName());
                        }
                        pContactPlan.setContactType(CommonConstants.PURCHASE_ITEM_TYPE_SPECIAL);
                        saveOrUpdatePContactPlan(pContactPlan);
                    }
                }
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取项目分期列表
     */
    @Override
    public RestReturnResult getProjectPhasesList() throws Exception {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);

        try {

            List<String> list = extPContactPlanMapper.getProjectPhasesList();

            restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS, list);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------getProjectPhasesList-------e-----:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return restResult;
    }

    @Override
    public List<ExtPContactPlan> selectByDetailId(String id) {
        List<ExtPContactPlan> list = extPContactPlanMapper.selectByDetailId(id);
        return list;

    }

    /***
     * 从成本系统中同步合约规划
     * @param lstPContactPlanVo
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public RestReturnResult doSynContactPlanFromCostSystem(List<PContactPlanVo> lstPContactPlanVo) {
        RestReturnResult restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[0], CommonConstants.ERROR_DESCS[0]);
        try {
            System.out.println("-------doSynContactPlanFromCostSystem------------");
            if (CollectionUtils.isNotEmpty(lstPContactPlanVo)) {
                Gson gson = new Gson();
                System.out.println("-------doSynContactPlanFromCostSystem------------:" + gson.toJson(lstPContactPlanVo));
                sAbutmentLogsService.saveAbutmentLogs(CallBackAbutmentTypeEnum.CallBackAbutmentTypeEnum_8.getCode(), "", JSONArray.toJSONString(lstPContactPlanVo), 1, 0);

                for (PContactPlanVo item : lstPContactPlanVo) {
                    if (item.getContactType() != null && item.getContactType() == CommonConstants.PURCHASE_ITEM_TYPE_SPECIAL) {///专项招标项
                        saveOrUpdatePContactPlan(item);

                    } else if (item.getContactType() != null && item.getContactType() == CommonConstants.PURCHASE_ITEM_TYPE_STRATEGY) {///战略招标项
                        saveOrUpdatePStrategicPurchaseContact(item);
                    }
                    restResult = new RestReturnResult<Object>(CommonConstants.SUCCESS);
                }
            } else {
                restResult = new RestReturnResult<Object>(CommonConstants.FAIL, CommonConstants.ERROR_CODES[4], CommonConstants.ERROR_DESCS[4]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("-------doSynContactPlanFromCostSystem-------e-----:" + e.getMessage());
            System.out.println("-------doSynContactPlanFromCostSystem------------:" + e.getMessage());
            throw new RuntimeException(e);
        }
        return restResult;
    }

    /***
     * 从成本系统中同步合约规划 - 专项采购
     * @param item
     */
    public void saveOrUpdatePContactPlan(PContactPlanVo item) {
        String id = "";
        boolean isNew = true;
        Map<String, Object> mapParams = new HashMap<String, Object>();
        mapParams.put("contractId", item.getContractId());
        List<ExtPContactPlan> lstExtPContactPlan = extPContactPlanMapper.getPContractPlanByMaps(mapParams);
        if (CollectionUtils.isNotEmpty(lstExtPContactPlan)) {
            id = lstExtPContactPlan.get(0).getId();
            isNew = false;
        }

        if (NumberUtils.toInteger(item.getDelFlag()) == CommonConstants.YES_INTEGER) {
            if (StringUtils.isNotEmpty(id)) {
                PContactPlan pContactPlan = new PContactPlan();
                pContactPlan.setId(id);
                updateById(pContactPlan);
            }
        } else {
            ///
            PContactPlan pContactPlan = new PContactPlan();
            if (isNew) {
                pContactPlan.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, true);
                pContactPlan.setPlanStatus(CommonConstants.NO_INTEGER);
            } else {
                pContactPlan.setId(id);
                pContactPlan.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, false);
            }

            if (StringUtils.isNotEmpty(item.getProjectCode())) {
                List<SProject> lstSProject = sProjectService.getSProjectByCodeAndRegionalCompanyId(item.getProjectCode(), null, null);
                if (CollectionUtils.isNotEmpty(lstSProject)) {
                    SCompany scompany = sCompanyService.selectById(lstSProject.get(0).getCompanyId());
                    pContactPlan.setProjectId(lstSProject.get(0).getId());
                    pContactPlan.setRegionalCompanyId(lstSProject.get(0).getRegionalCompanyId());
                    pContactPlan.setCompanyId(lstSProject.get(0).getCompanyId());
                    pContactPlan.setCompanyName(scompany.getCompanyName());
                }
            }

            pContactPlan.setProjectCode(item.getProjectCode());
            pContactPlan.setProjectName(item.getProjectName());
            pContactPlan.setProjectByStageCode(item.getProjectByStageCode());
            pContactPlan.setProjectByStage(item.getProjectByStage());
            pContactPlan.setContractId(item.getContractId());
            pContactPlan.setContractDetailId(item.getContractDetailId());
            pContactPlan.setContractName(item.getContractName());
            pContactPlan.setContractCode(item.getContractCode());
            pContactPlan.setPlanBudgetPrices(item.getPlanBudgetPrices());
//						pContactPlan.setPlanBudgetTime(DateUtils.parseDate(item.getPlanBudgetTime(),DateUtils.DATE_TIME));
            pContactPlan.setSynStatus(item.getMbsStatus());
            if (item.getPurchaseType() != null) {
                pContactPlan.setPurchaseType(PurchasePlanFlowTypeEnum.getKeyBySynCode(item.getPurchaseType()));
            }
            if (isNew) {
                insert(pContactPlan);
            } else {
                updateById(pContactPlan);
            }
        }
    }

    /***
     * 从成本系统中同步合约规划 - 战略采购
     * @param item
     */
    public void saveOrUpdatePStrategicPurchaseContact(PContactPlanVo item) {
        String id = "";
        boolean isNew = true;
        Map<String, Object> mapParams = new HashMap<String, Object>();
        mapParams.put("contractId", item.getContractId());
        List<PStrategicPurchaseContact> lstPStrategicPurchaseContact = pStrategicPurchaseContactService.getStrategicPurchaseContractPlanByMaps(mapParams);
        if (CollectionUtils.isNotEmpty(lstPStrategicPurchaseContact)) {
            id = lstPStrategicPurchaseContact.get(0).getId();
            isNew = false;
        }
        if (NumberUtils.toInteger(item.getDelFlag()) == CommonConstants.YES_INTEGER) {
            if (StringUtils.isNotEmpty(id)) {
                PStrategicPurchaseContact pStrategicPurchaseContact = new PStrategicPurchaseContact();
                pStrategicPurchaseContact.setId(id);
                pStrategicPurchaseContact.setBaseFeilds(null, "delete by interface", CommonConstants.YES_INTEGER, false);
                pStrategicPurchaseContactService.updateById(pStrategicPurchaseContact);
            }
        } else {
            ///
            PStrategicPurchaseContact pStrategicPurchaseContact = new PStrategicPurchaseContact();
            if (isNew) {
                pStrategicPurchaseContact.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, true);
                pStrategicPurchaseContact.setPurchaseItemStatus(CommonConstants.NO_INTEGER);
            } else {
                pStrategicPurchaseContact.setId(id);
                pStrategicPurchaseContact.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, false);
            }

            if (StringUtils.isNotEmpty(item.getProjectCode())) {
                List<SProject> lstSProject = sProjectService.getSProjectByCodeAndRegionalCompanyId(item.getProjectCode(), null, null);
                if (CollectionUtils.isNotEmpty(lstSProject)) {
                    pStrategicPurchaseContact.setProjectId(lstSProject.get(0).getId());
                    pStrategicPurchaseContact.setRegionalCompanyId(lstSProject.get(0).getRegionalCompanyId());
                    pStrategicPurchaseContact.setCompanyId(lstSProject.get(0).getCompanyId());
                    //主责部门（集团或地区公司id）
                    pStrategicPurchaseContact.setResponsibilityId(lstSProject.get(0).getRegionalCompanyId());
                }
            }

            pStrategicPurchaseContact.setProjectName(item.getProjectName());
            pStrategicPurchaseContact.setContractId(item.getContractId());
            pStrategicPurchaseContact.setContractName(item.getContractName());
            pStrategicPurchaseContact.setContractCode(item.getContractCode());
            pStrategicPurchaseContact.setPlanBudgetPrices(item.getPlanBudgetPrices());
            pStrategicPurchaseContact.setSynStatus(item.getMbsStatus());
            if (item.getPurchaseType() != null)
                pStrategicPurchaseContact.setPurchaseType(PurchasePlanFlowTypeEnum.getKeyBySynCode(item.getPurchaseType()));

//			//主责部门（集团或地区公司id）
//			List<ExtSRegionalCompany> lstExtSRegionalCompany = sRegionalCompanyService.getGroupRegionalCompany();
//			if(CollectionUtils.isNotEmpty(lstExtSRegionalCompany)){
//				pStrategicPurchaseContact.setResponsibilityId(lstExtSRegionalCompany.get(0).getId());
//			}

            if (isNew) {
                pStrategicPurchaseContactService.insert(pStrategicPurchaseContact);
            } else {
                pStrategicPurchaseContactService.updateById(pStrategicPurchaseContact);
            }
        }

    }

}
